package com.luych.toolbox.docker.service.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.luych.toolbox.common.enums.TaskStatus;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketEventPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketLetterPublisher;
import com.luych.toolbox.common.event.base.service.publisher.WebSocketNoticePublisher;
import com.luych.toolbox.common.feign.intf.base.service.TaskFeign;
import com.luych.toolbox.common.feign.intf.base.service.TaskLogFeign;
import com.luych.toolbox.common.feign.param.base.service.TaskLogParam;
import com.luych.toolbox.common.feign.param.gateway.center.WebSocketEvent;
import com.luych.toolbox.common.feign.view.base.service.TaskView;
import com.luych.toolbox.docker.service.entity.DockerServer;
import com.luych.toolbox.docker.service.sdk.DockerClient;
import com.luych.toolbox.docker.service.sdk.image.model.DockerImagesPullResult;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class DockerImagePullJob extends QuartzJobBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(DockerImagePullJob.class);

    private final BusProperties busProperties;
    private final ApplicationEventPublisher applicationEventPublisher;

    private final TaskFeign taskFeign;
    private final TaskLogFeign taskLogFeign;

    public DockerImagePullJob(BusProperties busProperties,
                              ApplicationEventPublisher applicationEventPublisher,
                              TaskFeign taskFeign,
                              TaskLogFeign taskLogFeign) {
        this.busProperties = busProperties;
        this.applicationEventPublisher = applicationEventPublisher;
        this.taskFeign = taskFeign;
        this.taskLogFeign = taskLogFeign;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String id = context.getJobDetail().getJobDataMap().getString("id");

        WebSocketLetterPublisher letterPublisher = new WebSocketLetterPublisher(busProperties, applicationEventPublisher);
        WebSocketNoticePublisher noticePublisher = new WebSocketNoticePublisher(busProperties, applicationEventPublisher);
        WebSocketEventPublisher eventPublisher = new WebSocketEventPublisher(busProperties, applicationEventPublisher);

        TaskView task = taskFeign.get(id);
        Param stdin = Param.fromJson(task.getStdin());

        Consumer<DockerImagesPullResult> consumer = dockerImagesPullResult -> {
            LOGGER.info("Docker[{}]: {}", stdin.getServer().getName(), dockerImagesPullResult.toString());
            TaskLogParam taskLog = new TaskLogParam();
            taskLog.setTaskId(task.getId());
            taskLog.setLog(dockerImagesPullResult.toString());
            taskLogFeign.create(taskLog);
        };

        taskFeign.start(task.getId());

        String message = "拉取镜像通知";

        DockerClient dockerClient = new DockerClient(stdin.getServer().getUrl());
        try {
            List<DockerImagesPullResult> results = dockerClient.images().pull(stdin.getImage(), consumer, stdin.getUser(), stdin.getPass());
            String stdout = results.stream().map(DockerImagesPullResult::toString).collect(Collectors.joining("\r\n"));
            taskFeign.complete(task.getId(), TaskStatus.SUCCESS, stdout);
            LOGGER.info("docker server {} pull image {} success", stdin.getServer().getName(), stdin.getImage());

            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
            String content = "容器宿主机[" + stdin.getServer().getName() + "]拉取镜像[" + stdin.getImage() + "]任务于" + datetime + "执行成功！";
            noticePublisher.success(task.getOwnerId(), content);
            letterPublisher.success(task.getOwnerId(), message, content);
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_IMAGE_REFRESH, "PULL"));
        } catch (Exception e) {
            LOGGER.error("docker server {} pull image {} error: {}", stdin.getServer().getName(), stdin.getImage(), e.getMessage());
            StringWriter writer = new StringWriter();
            e.printStackTrace(new PrintWriter(writer));

            taskFeign.complete(task.getId(), TaskStatus.ERROR, e.getMessage());

            String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
            String content = "容器宿主机[" + stdin.getServer().getName() + "]拉取镜像[" + stdin.getImage() + "]任务于" + datetime + "执行异常，请及时处理。";
            noticePublisher.error(task.getOwnerId(), content);
            content += "\n\n\n错误信息：\n" + e.getMessage() + "\n\n\n异常堆栈：\n" + writer.toString();
            letterPublisher.error(task.getOwnerId(), message, content);
            eventPublisher.send(new WebSocketEvent(WebSocketEvent.Type.DOCKER_IMAGE_REFRESH, "PULL"));
        }
    }

    public static class Param {
        private DockerServer server;
        private String image;
        private String user;
        private String pass;

        public DockerServer getServer() {
            return server;
        }

        public void setServer(DockerServer server) {
            this.server = server;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getUser() {
            return user;
        }

        public void setUser(String user) {
            this.user = user;
        }

        public String getPass() {
            return pass;
        }

        public void setPass(String pass) {
            this.pass = pass;
        }

        public String toJson() {
            try {
                return new ObjectMapper().writeValueAsString(this);
            } catch (JsonProcessingException e) {
                throw new IllegalStateException(e);
            }
        }

        public static Param fromJson(String json) {
            try {
                return new ObjectMapper().readValue(json, Param.class);
            } catch (JsonProcessingException e) {
                throw new IllegalStateException(e);
            }
        }
    }
}
